package com.athl.netty.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapte
 * httpObject : 客户端和服务器端互相通信的数据被封装成 HttpObject
 *
 * @author hl
 * @Data 2020/9/1
 */
public class TestHttpHandlerServer extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取客户端数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest) {
            System.out.println("msg 类型" + msg.getClass());
            System.out.println("客户端数据" + ctx.channel().remoteAddress());
            // 如果不想发送请求 favicon.ico
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if ("/favicon.ico".equals(uri.getPath())) {
                System.out.println("请求了 favicon,但是不处理");
                return;
            }
            // 每次发送请求的 pipeline 和 handler 都是不同的
            // 回复信息给浏览器
            ByteBuf context = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);
            // 构造http响应
            DefaultFullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, context);
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, context.readableBytes());
            // 将构建好的Response返回
            ctx.writeAndFlush(fullHttpResponse);
        }
    }
}
